package com.ruoyi.file.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.file.domain.SysStorageConfig;
import com.ruoyi.file.service.ISysStorageConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 存储配置Controller
 *
 * @author ruoyi
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/file/storage/config")
@Tag(name = "存储配置管理", description = "存储配置管理相关接口")
public class SysStorageConfigController extends BaseController {

    private final ISysStorageConfigService storageConfigService;

    /**
     * 查询存储配置列表
     */
    @Operation(summary = "查询存储配置列表")
    @SaCheckPermission("file:storage:list")
    @GetMapping("/list")
    public TableDataInfo list(SysStorageConfig sysStorageConfig) {
        startPage();
        List<SysStorageConfig> list = storageConfigService.selectStorageConfigList(sysStorageConfig);
        return getDataTable(list);
    }

    /**
     * 导出存储配置列表
     */
    @Operation(summary = "导出存储配置列表")
    @SaCheckPermission("file:storage:export")
    @Log(title = "存储配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysStorageConfig sysStorageConfig) {
        List<SysStorageConfig> list = storageConfigService.selectStorageConfigList(sysStorageConfig);
        ExcelUtil<SysStorageConfig> util = new ExcelUtil<>(SysStorageConfig.class);
        util.exportExcel(response, list, "存储配置数据");
    }

    /**
     * 获取存储配置详细信息
     */
    @Operation(summary = "获取存储配置详细信息")
    @SaCheckPermission("file:storage:query")
    @GetMapping(value = "/{configId}")
    public AjaxResult getInfo(@Parameter(description = "配置ID") @PathVariable("configId") Long configId) {
        return AjaxResult.success(storageConfigService.getById(configId));
    }

    /**
     * 新增存储配置
     */
    @Operation(summary = "新增存储配置")
    @SaCheckPermission("file:storage:add")
    @Log(title = "存储配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysStorageConfig sysStorageConfig) {
        // 针对非本地存储类型验证必填字段
        validateStorageConfig(sysStorageConfig);
        return toAjax(storageConfigService.insertStorageConfig(sysStorageConfig));
    }

    /**
     * 修改存储配置
     */
    @Operation(summary = "修改存储配置")
    @SaCheckPermission("file:storage:edit")
    @Log(title = "存储配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysStorageConfig sysStorageConfig) {
        // 针对非本地存储类型验证必填字段
        validateStorageConfig(sysStorageConfig);
        return toAjax(storageConfigService.updateStorageConfig(sysStorageConfig));
    }

    /**
     * 删除存储配置
     */
    @Operation(summary = "删除存储配置")
    @SaCheckPermission("file:storage:remove")
    @Log(title = "存储配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{configIds}")
    public AjaxResult remove(@Parameter(description = "配置ID数组") @PathVariable Long[] configIds) {
        return toAjax(storageConfigService.deleteStorageConfigByIds(configIds));
    }

    /**
     * 设置默认存储配置
     */
    @Operation(summary = "设置默认存储配置")
    @SaCheckPermission("file:storage:edit")
    @Log(title = "存储配置", businessType = BusinessType.UPDATE)
    @PutMapping("/setDefault/{configId}")
    public AjaxResult setDefault(@Parameter(description = "配置ID") @PathVariable("configId") Long configId) {
        // 获取配置信息
        SysStorageConfig config = storageConfigService.getById(configId);
        if (config == null) {
            return AjaxResult.error("存储配置不存在");
        }
        // 检查配置是否为启用状态
        if (config.getStatus() == null || config.getStatus() != 1) {
            return AjaxResult.error("只能设置启用状态的存储配置为默认配置");
        }
        boolean result = storageConfigService.setDefaultConfig(configId);
        return result ? AjaxResult.success("设置默认配置成功") : AjaxResult.error("设置默认配置失败");
    }

    /**
     * 测试存储配置连接
     */
    @Operation(summary = "测试存储配置连接")
    @SaCheckPermission("file:storage:test")
    @Log(title = "存储配置", businessType = BusinessType.OTHER)
    @PostMapping("/test")
    public AjaxResult testConnection(@Validated @RequestBody SysStorageConfig sysStorageConfig) {
        boolean result = storageConfigService.testConnection(sysStorageConfig);
        return result ? AjaxResult.success("连接测试成功") : AjaxResult.error("连接测试失败");
    }

    /**
     * 获取默认存储配置
     */
    @Operation(summary = "获取默认存储配置")
    @SaCheckPermission("file:storage:query")
    @GetMapping("/default")
    public AjaxResult getDefaultConfig() {
        SysStorageConfig defaultConfig = storageConfigService.getDefaultConfig();
        return AjaxResult.success(defaultConfig);
    }

    /**
     * 修改存储配置状态
     */
    @Operation(summary = "修改存储配置状态")
    @SaCheckPermission("file:storage:edit")
    @Log(title = "存储配置", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysStorageConfig sysStorageConfig) {
        if (sysStorageConfig.getConfigId() == null) {
            return AjaxResult.error("配置ID不能为空");
        }
        SysStorageConfig originalConfig = storageConfigService.getById(sysStorageConfig.getConfigId());
        if (originalConfig == null) {
            return AjaxResult.error("存储配置不存在");
        }
        // 如果要停用配置，检查是否为默认配置
        if (sysStorageConfig.getStatus() != null && sysStorageConfig.getStatus() == 0) {
            if (originalConfig.getIsDefault() != null && originalConfig.getIsDefault() == 1) {
                return AjaxResult.error("默认存储配置不能停用，请先设置其他配置为默认");
            }
        }

        // 如果要启用非本地存储，需要先测试连接
        if (sysStorageConfig.getStatus() != null && sysStorageConfig.getStatus() == 1 && !"local".equals(originalConfig.getStorageType())) {
            boolean testResult = storageConfigService.testConnection(originalConfig);
            if (!testResult) {
                return AjaxResult.error("连接测试失败，无法启用该存储配置");
            }
        }
        SysStorageConfig updateConfig = new SysStorageConfig();
        updateConfig.setConfigId(sysStorageConfig.getConfigId());
        updateConfig.setStatus(sysStorageConfig.getStatus());
        boolean result = storageConfigService.updateStorageConfig(updateConfig) > 0;
        return result ? AjaxResult.success("状态修改成功") : AjaxResult.error("状态修改失败");
    }

    /**
     * 验证存储配置
     */
    private void validateStorageConfig(SysStorageConfig config) {
        if (!"local".equals(config.getStorageType())) {
            // 非本地存储类型需要验证 endpoint、accessKey 和 secretKey
            if (StringUtils.isBlank(config.getEndpoint())) {
                throw new ServiceException("访问端点不能为空");
            }
            if (StringUtils.isBlank(config.getAccessKey())) {
                throw new ServiceException("访问密钥不能为空");
            }
            if (StringUtils.isBlank(config.getSecretKey())) {
                throw new ServiceException("秘密密钥不能为空");
            }
        }
    }
}
